package ctx

import (
	"context"
	"framework/gredis"
	"framework/httpz/client"
	"framework/httpz/response"
	"net/http"
	"time"

	"github.com/kataras/iris/v12"
)

func DemoEcho(ctx iris.Context) {

	// 原始请求
	// body, _ := ctx.GetBody()

	// 设置cookie
	response.SetCookie(ctx, &http.Cookie{
		Name:     "auth_token",
		Value:    "asdfsdf",
		Secure:   true,
		HttpOnly: true,
		SameSite: http.SameSiteLaxMode,
	})

	response.Sucess(ctx, iris.Map{
		"method":    ctx.Request().Method, // Method
		"headers":   ctx.Request().Header, // Headers
		"params":    ctx.URLParams(),      // Get 参数
		"form":      ctx.FormValues(),     // Get/Post参数, 不能接收bin数据
		"unix_time": time.Now().Format(time.RFC3339),
	})
}

func UrlEcho(ctx iris.Context) {
	result := struct {
		Data    any
		Errno   int
		Message string
	}{}

	// 创建client
	c := client.Default()

	// 创建Request
	request := client.NewRequest()
	request.Post("http://127.0.0.1:6800/v1/demo/echo?type=1", nil)
	request.Header.Set("abd", "12e12")

	// 处理请求
	e := c.Do(request, func(resp *client.Response) {
		// 获取返回数据
		resp.UnmarshalBody(&result)
	})

	// 返回错误
	if e != nil {
		response.Error(ctx, 3001021, e)
		return
	}

	response.Sucess(ctx, iris.Map{
		"response":  result,
		"unix_time": time.Now().Format(time.RFC3339),
	})
}

func RedisDemo(ctx iris.Context) {
	// 创建客户端
	c := gredis.NewClient(&gredis.Options{
		Addr: "127.0.0.1:6379",
	})
	defer c.Close()

	ctb := context.Background()

	// 处理请求
	c.Set(ctb, "abc", "12345", 0*time.Second)

	response.Sucess(ctx, iris.Map{
		"unix_time": time.Now().Format(time.RFC3339),
	})
}

func RedisLock(ctx iris.Context) {
	// 创建客户端
	c := gredis.NewClient(&gredis.Options{
		Addr: "127.0.0.1:6379",
	})
	defer c.Close()

	ctb := context.Background()
	key := "abc_demo"
	lockId := "laksdfo123"
	expire := 10 * time.Second

	c.RenewableLock(ctb, key, lockId, expire)
	c.RenewableLock(ctb, key, lockId, expire)
	c.RenewableLock(ctb, key, "12keo12i", expire)
	c.UnLock(ctb, key, lockId)

	response.Sucess(ctx, iris.Map{
		"unix_time": time.Now().Format(time.RFC3339),
	})
}

// redis 普通锁
func RedisLock2(ctx iris.Context) {
	// 创建客户端
	c := gredis.NewClient(&gredis.Options{
		Addr: "127.0.0.1:6379",
	})
	defer c.Close()

	ctb := context.Background()
	key := "abc_123"
	lockId := "laksdfo123"
	expire := 10 * time.Second

	// 处理锁
	lock, _ := c.Lock(ctb, key, lockId, expire)
	defer c.UnLock(ctb, key, lockId)

	// 加锁成功
	if lock == true {
		// 处理业务
	}

	response.Sucess(ctx, iris.Map{
		"unix_time": time.Now().Format(time.RFC3339),
	})
}
